package com.tony.study.thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: CallableDemo01
 * @Auther: 皮蛋布丁
 * @Date: 2021/10/30/22:18
 * @Description: 线程创建方式三：实现callable接口
 * Callable好处：可以定义返回值；可以抛出异常
 */
public class CallableDemo01 implements Callable<Boolean> {

    private String url; //网络图片地址
    private String name;    //保存的文件名

    public CallableDemo01(String url, String name) {
        this.url = url;
        this.name = name;
    }

    //下载图片的线程执行体
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为："+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableDemo01 t1 = new CallableDemo01("https://avatar.csdnimg.cn/F/7/6/1_qq_42700766_1578631082.jpg","1.jpg");
        CallableDemo01 t2 = new CallableDemo01("https://avatar.csdnimg.cn/F/7/6/1_qq_42700766_1578631082.jpg","2.jpg");
        CallableDemo01 t3 = new CallableDemo01("https://avatar.csdnimg.cn/F/7/6/1_qq_42700766_1578631082.jpg","3.jpg");

        //创建执行服务：
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        //获取结果
        boolean rs1 =r1.get();
        boolean rs2 =r2.get();
        boolean rs3 =r3.get();
        //关闭服务
        ser.shutdownNow();
    }
}